<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">库存管理</h1>
      <n-button type="primary" @click="showStockModal = true">
        <template #icon>
          <n-icon><SwapHorizontalOutline /></n-icon>
        </template>
        库存变动
      </n-button>
    </div>
    
    <!-- 库存列表 -->
    <n-card title="库存列表" style="margin-bottom: 24px;">
      <n-data-table
        :columns="breadColumns"
        :data="breadList"
        :loading="breadLoading"
        :bordered="false"
      />
    </n-card>
    
    <!-- 变动记录 -->
    <n-card title="变动记录">
      <n-space style="margin-bottom: 16px;">
        <n-date-picker 
          v-model:value="searchParams.dateRange" 
          type="datetimerange" 
          clearable 
          placeholder="选择时间范围"
          style="width: 360px;"
        />
        <n-button type="primary" @click="handleSearch">搜索</n-button>
        <n-button @click="handleReset">重置</n-button>
      </n-space>
      
      <n-data-table
        :columns="recordColumns"
        :data="recordList"
        :loading="recordLoading"
        :pagination="pagination"
        :bordered="false"
        @update:page="handlePageChange"
      />
    </n-card>
    
    <!-- 库存变动对话框 -->
    <n-modal v-model:show="showStockModal" preset="dialog" title="库存变动" style="width: 500px;">
      <n-form ref="formRef" :model="formData" :rules="rules" label-placement="left" label-width="100">
        <n-form-item label="面包" path="breadId">
          <n-select 
            v-model:value="formData.breadId" 
            :options="breadOptions" 
            placeholder="请选择面包"
            filterable
          />
        </n-form-item>
        <n-form-item label="变动类型" path="changeType">
          <n-radio-group v-model:value="formData.changeType">
            <n-radio value="入库">入库</n-radio>
            <n-radio value="出库">出库</n-radio>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="变动数量" path="quantity">
          <n-input-number v-model:value="formData.quantity" :min="1" placeholder="请输入数量" style="width: 100%;">
            <template #suffix>个</template>
          </n-input-number>
        </n-form-item>
        <n-form-item label="备注">
          <n-input v-model:value="formData.remark" type="textarea" placeholder="选填" :rows="3" />
        </n-form-item>
      </n-form>
      
      <template #action>
        <n-space>
          <n-button @click="showStockModal = false">取消</n-button>
          <n-button type="primary" @click="handleSubmit">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, h, onMounted, reactive, computed } from 'vue'
import { getBreadList, changeStock, getStockRecordPage } from '@/api/bread'
import { 
  NCard, NButton, NIcon, NSpace, NDatePicker, NDataTable, NTag, NModal,
  NForm, NFormItem, NSelect, NRadioGroup, NRadio, NInputNumber, NInput, useMessage
} from 'naive-ui'
import { SwapHorizontalOutline, ArrowUpOutline, ArrowDownOutline } from '@vicons/ionicons5'

const message = useMessage()

const breadLoading = ref(false)
const recordLoading = ref(false)
const breadList = ref([])
const recordList = ref([])
const showStockModal = ref(false)
const formRef = ref(null)

const searchParams = reactive({
  dateRange: null
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})

const formData = ref({
  breadId: null,
  changeType: '入库',
  quantity: null,
  remark: ''
})

const rules = {
  breadId: { required: true, type: 'number', message: '请选择面包', trigger: 'change' },
  changeType: { required: true, message: '请选择变动类型', trigger: 'change' },
  quantity: { required: true, type: 'number', message: '请输入数量', trigger: 'blur' }
}

const breadOptions = computed(() => {
  return breadList.value.map(bread => ({
    label: `${bread.name}（当前库存：${bread.stock}）`,
    value: bread.id
  }))
})

const breadColumns = [
  { title: '名称', key: 'name' },
  { 
    title: '分类', 
    key: 'category',
    render: (row) => {
      const colorMap = { '甜面包': 'warning', '咸面包': 'info', '吐司': 'success' }
      return h(NTag, { type: colorMap[row.category] }, { default: () => row.category })
    }
  },
  { 
    title: '库存', 
    key: 'stock',
    render: (row) => {
      const type = row.stock > 20 ? 'success' : row.stock > 0 ? 'warning' : 'error'
      return h(NTag, { type, size: 'large' }, { default: () => row.stock })
    }
  },
  { 
    title: '单价', 
    key: 'price',
    render: (row) => `¥${row.price}`
  },
  { 
    title: '状态', 
    key: 'status',
    render: (row) => {
      return h(NTag, { type: row.status === 1 ? 'success' : 'default' }, { 
        default: () => row.status === 1 ? '在售' : '已下架' 
      })
    }
  }
]

const recordColumns = [
  { title: '面包ID', key: 'breadId', width: 100 },
  { 
    title: '变动类型', 
    key: 'changeType',
    render: (row) => {
      const typeMap = {
        '入库': { type: 'success', icon: ArrowUpOutline },
        '出库': { type: 'warning', icon: ArrowDownOutline },
        '销售': { type: 'info', icon: ArrowDownOutline }
      }
      const config = typeMap[row.changeType]
      return h(NTag, { type: config.type }, {
        default: () => row.changeType,
        icon: () => h(NIcon, {}, { default: () => h(config.icon) })
      })
    }
  },
  { 
    title: '变动数量', 
    key: 'changeQuantity',
    render: (row) => {
      const color = row.changeQuantity > 0 ? '#18a058' : '#d03050'
      return h('span', { style: { color, fontWeight: 600 } }, 
        row.changeQuantity > 0 ? `+${row.changeQuantity}` : row.changeQuantity
      )
    }
  },
  { title: '变动前库存', key: 'beforeStock' },
  { title: '变动后库存', key: 'afterStock' },
  { title: '备注', key: 'remark', ellipsis: { tooltip: true } },
  { title: '操作时间', key: 'createTime', width: 180 }
]

async function loadBreadList() {
  try {
    breadLoading.value = true
    const res = await getBreadList()
    breadList.value = res.data
  } catch (error) {
    message.error(error.message || '加载面包列表失败')
  } finally {
    breadLoading.value = false
  }
}

async function loadRecordList() {
  try {
    recordLoading.value = true
    const params = {
      page: pagination.page,
      size: pagination.pageSize
    }
    
    if (searchParams.dateRange && searchParams.dateRange.length === 2) {
      params.startTime = new Date(searchParams.dateRange[0]).toISOString().slice(0, 19).replace('T', ' ')
      params.endTime = new Date(searchParams.dateRange[1]).toISOString().slice(0, 19).replace('T', ' ')
    }
    
    const res = await getStockRecordPage(params)
    recordList.value = res.data.records
    pagination.itemCount = res.data.total
  } catch (error) {
    message.error(error.message || '加载变动记录失败')
  } finally {
    recordLoading.value = false
  }
}

function handleSearch() {
  pagination.page = 1
  loadRecordList()
}

function handleReset() {
  searchParams.dateRange = null
  pagination.page = 1
  loadRecordList()
}

function handlePageChange(page) {
  pagination.page = page
  loadRecordList()
}

async function handleSubmit() {
  try {
    await formRef.value?.validate()
    await changeStock(formData.value)
    message.success('库存变动成功')
    showStockModal.value = false
    formData.value = {
      breadId: null,
      changeType: '入库',
      quantity: null,
      remark: ''
    }
    loadBreadList()
    loadRecordList()
  } catch (error) {
    if (error.message) {
      message.error(error.message)
    }
  }
}

onMounted(() => {
  loadBreadList()
  loadRecordList()
})
</script>

